//
//  UserDefaultsManager.m
//  DuoDian
//
//  Created by 张卓 on 2017/8/16.
//  Copyright © 2017年 bigcastcloudShop. All rights reserved.
//

#import "UserDefaultsManager.h"

NSString *const BCUserDefaultsManagerFirstLaunch = @"firstLaunch";
NSString *const BCUserDefaultsManagerUserLoggedIn = @"userLoggedIn";
NSString *const BCUserDefaultsManagerCurrentVersion = @"currentVersion";


@implementation UserDefaultsManager
+ (instancetype)shareUserDefaultsManager {
    static UserDefaultsManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[UserDefaultsManager alloc] init];
    });
    return manager;
}

- (BOOL)isFirstLaunch {
    return [self boolForKey:BCUserDefaultsManagerFirstLaunch defaultValue:YES];
}

- (void)setFirstLaunch {
    [self setBool:NO forKey:BCUserDefaultsManagerFirstLaunch];
}

- (BOOL)isUserLoggedIn {
    return [self boolForKey:BCUserDefaultsManagerUserLoggedIn defaultValue:NO];
}

- (void)setUserLoggedIn {
    [self setBool:YES forKey:BCUserDefaultsManagerUserLoggedIn];
}

- (void)setUserLoggedOut {
    [self setBool:NO forKey:BCUserDefaultsManagerUserLoggedIn];
}

- (BOOL)hasCurrentVersion {
    NSString *currentVersion = [self getCurrenVersion];
    if ([currentVersion isEqualToString:[self stringForKey:BCUserDefaultsManagerCurrentVersion]]) {
        return YES;
    }
    return NO;
}

- (void)setCurrentVersion {
    [self setObject:[self getCurrenVersion] forKey:BCUserDefaultsManagerCurrentVersion];
}

- (void)removeObjectForKey:(NSString *)aKey {
    UserDefaults(userDefaults);
    [userDefaults removeObjectForKey:aKey];
    [userDefaults synchronize];
}


#pragma mark - private
- (void)setBool:(BOOL)value forKey:(NSString *)aKey {
    UserDefaults(userDefaults);
    [userDefaults setBool:value forKey:aKey];
    [userDefaults synchronize];
}

- (void)setObject:(id)anObject forKey:(NSString *)akey {
    UserDefaults(userDefaults);
    [userDefaults setObject:anObject forKey:akey];
    [userDefaults synchronize];
}

- (BOOL)boolForKey:(NSString *)aKey defaultValue:(BOOL)defaultValue {
    UserDefaults(userDefaults);
    if (![userDefaults objectForKey:aKey]) {
        return defaultValue;
    }
    return [[userDefaults objectForKey:aKey] boolValue];
}

- (NSString *)stringForKey:(NSString *)aKey {
    UserDefaults(userDefaults);
    return [userDefaults stringForKey:aKey];
}

- (nullable NSDictionary<NSString *, id> *)dictionaryForKey:(NSString *)aKey{
    UserDefaults(userDefaults);
    return [userDefaults dictionaryForKey:aKey];
}

- (NSString *)getCurrenVersion {
    return [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
}
@end
